<template>
  <div class="app-container org">
    <el-card>
      <el-form ref="queryRef" label-width="100" :model="queryParams">
        <el-form-item label="当前应用：" prop="appName" label-width="80">
          <el-select clearable v-model="queryParams.id" placeholder="请选择当前应用" filterable @change="handleQuery1">
            <el-option v-for="item in proxy.addListNoLimit(appList, 'id', 'appName')" :key="item.id" :label="item.appName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <p class="pinformation">搜索条件</p>
        <el-row>
          <el-col :span="5">
            <el-form-item label="版本号：" prop="version" label-width="80">
              <el-input clearable maxlength="100" placeholder="请输入版本号" v-model="queryParams.version"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-row justify="end">
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">版本列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-dropdown trigger="click" @command="handleSetSize">
            <el-button type="success" link>发布新版</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) of packageOptions" :key="item.value" :command="item.value"
                  :disabled="index == 1">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-row>
        <el-table ref="mainTableRef" :data="appTable" v-loading="appLoading">
          <el-table-column label="AppID" prop="appId" align="center" />
          <el-table-column label="更改标题" prop="title" align="center" />
          <el-table-column label="安装包类型" prop="packageType" align="center">
            <template #default="scope">
              {{ scope.row.packageType ? "wgt资源包" : "原生APP安装包" }}
            </template>
          </el-table-column>
          <el-table-column label="平台" prop="platform" align="center">
            <template #default="scope">
              {{ scope.row.platform ? "苹果" : "安卓" }}
            </template>
          </el-table-column>
          <el-table-column label="版本号" prop="version" align="center" />
          <el-table-column label="安装包状态" prop="onlineRelease" align="center">
            <template #default="scope">
              {{ scope.row.onlineRelease ? "已上线" : "未上线" }}
            </template>
          </el-table-column>
          <el-table-column label="上传时间" prop="createTime" align="center" />
          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="xqApp(scope.row)">{{
                scope.row.onlineRelease === 0 ? "编辑" : "详情"
              }}</el-button>
              <el-button link type="success" @click="delApp(scope.row.versionId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      @close="closedInDialog" v-model="appOpen" :title="appTitle" width="1100">
      <p class="pinformation">基础信息</p>
      <el-form label-width="90" ref="rkOrYyRef" :model="form" :rules="rules" :disabled="disabled">
        <el-form-item label="包类型：" prop="appId">
          {{ form.packageType ? "wgt资源包" : "原生APP安装包" }}
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="AppID：" prop="appId">
              <el-input clearable maxlength="100" :disabled="true" v-model="form.appId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用名称：" prop="appName">
              <el-input clearable maxlength="100" v-model="form.appName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="更新标题：" prop="title">
          <el-input clearable placeholder="请输入更新标题" maxlength="100" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="更新内容：" prop="content">
          <el-input clearable :autosize="{ minRows: 3, maxRows: 7 }" type="textarea" placeholder="请输入更新内容"
            v-model="form.content" maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="平台：" prop="platform">
          <el-row justify="center">
            <el-radio :label="0" v-model="form.platform">安卓</el-radio>
            <el-radio :label="1" v-model="form.platform" :disabled="true">苹果</el-radio>
          </el-row>
        </el-form-item>
        <el-form-item label="版本号：" prop="version">
          <el-input clearable maxlength="100" v-model="form.version"></el-input>
        </el-form-item>
        <el-form-item label="上传apk包：" prop="fileList">
          <fileUpload v-model="form.fileList" :fileType="['apk']" :isDisplay="!disabled" @upOver="upOver" :authId="1">
          </fileUpload>
        </el-form-item>
        <el-form-item label="包地址：">
          <el-input clearable maxlength="100" v-model="form.packageAddress" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="强制更新：" prop="forceUpdate1">
          <el-switch v-model="form.forceUpdate1" style="--el-switch-on-color: #13ce66" />
        </el-form-item>
        <el-form-item label="上线发行：" prop="onlineRelease1">
          <el-switch v-model="form.onlineRelease1" style="--el-switch-on-color: #13ce66" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveApp" v-if="!disabled">保 存</el-button>
          <el-button type="danger" @click="appOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getListApp,
  listAppVersion,
  delAppListVersion,
  appViewFormVersion,
  postAppVersion,
} from "@/api/system/app";

const route = useRoute();

const { proxy } = getCurrentInstance();

const appTable = ref([]);
const appList = ref([]);
const appOpen = ref(false);
const appLoading = ref(false);
const appTitle = ref("");
const packageOptions = ref([
  { value: 0, label: "原生APP安装包" },
  { value: 1, label: "wgt资源包" },
]);

const data = reactive({
  form: {
    fileList: [],
    appId: route.query.appId,
    appName: route.query.appName,
    id: route.query.id,
    platform: 0,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: route.query.id,
  },
  rules: {
    appId: [{ required: true, message: "AppID不能为空", trigger: "blur" }],
    appName: [{ required: true, message: "应用名称不能为空", trigger: "blur" }],
    content: [{ required: true, message: "更新内容不能为空", trigger: "blur" }],
    platform: [{ required: true, message: "平台不能为空", trigger: "blur" }],
    version: [{ required: true, message: "版本号不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const total = ref(0);
const dateRange = ref([]);
function getList() {
  appLoading.value = true;
  listAppVersion(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      appLoading.value = false;
      appTable.value = res.rows;
      total.value = res.total;
    }
  );
}
getList();
getInfo();

function getInfo() {
  form.value.id = route.query.id;
  form.value.appId = route.query.appId;
  form.value.appName = route.query.appName;
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  dateRange.value = [];
  queryParams.value.id = "";
  proxy.resetForm("queryRef");
  handleQuery();
}

function delApp(id) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delAppListVersion(id).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      });
    })
    .catch(() => { });
}

const disabled = ref(false);

function xqApp(row) {
  appViewFormVersion(row.versionId).then((res) => {

    form.value = res.data;
    appOpen.value = true;
    form.value.forceUpdate1 = !!form.value.forceUpdate;
    form.value.onlineRelease1 = !!form.value.onlineRelease;
    if (row.onlineRelease) {
      disabled.value = true;
      appTitle.value = "版本详情";
    } else {
      disabled.value = false;
      appTitle.value = "编辑版本";
    }
  });
}

function closedInDialog() {
  proxy.$refs["rkOrYyRef"].clearValidate();
  form.value = {
    fileList: [],
    appId: form.value.appId,
    appName: form.value.appName,
    id: form.value.id,
    platform: 0,
  };
}

function saveApp() {
  if (!form.value.packageAddress && form.value.onlineRelease1) {
    proxy.$modal.msgError("线上发行时请上传安装包");
    return
  }
  proxy.$refs["rkOrYyRef"].validate((valid) => {
    if (valid) {
      form.value.forceUpdate = form.value.forceUpdate1 ? 1 : 0;
      form.value.onlineRelease = form.value.onlineRelease1 ? 1 : 0;
      postAppVersion(form.value).then((res) => {
        appOpen.value = false;
        proxy.$modal.msgSuccess("新增成功");
        getList();
      });
    }
  });
}

function handleSetSize(val) {
  if (!form.value.id) {
    proxy.$modal.msgError("没有选择当前应用");
    return;
  }
  appOpen.value = true;
  appTitle.value = "新增版本";
  disabled.value = false;
  form.value = {
    fileList: [],
    packageType: val,
    appId: form.value.appId,
    appName: form.value.appName,
    id: form.value.id,
    platform: 0,
  };
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

watch(
  () => route.query.id,
  () => {
    if (route.path == "/system/appVersion") {

      resetQuery();
    }
  }
);

getListApp().then((res) => {
  appList.value = res.data;
});

function handleQuery1(val) {
  if (val) {
    form.value.id = val;
    form.value.appId = proxy.getItemByArray(appList.value, "id", val, "appId");
    form.value.appName = proxy.getItemByArray(
      appList.value,
      "id",
      val,
      "appName"
    );
  } else {
    form.value.id = "";
    form.value.appId = "";
    form.value.appName = "";
  }
  handleQuery();
}

function upOver(val) {
  form.value.packageAddress = val.downloadUrl;
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 5px;
}
</style>
